import Main from './HModal'
import Vue from 'vue'
// 增加store依赖
import store from '@/store'

// 存放嵌套
var modalStack = []

var HModal = (options = {}) => {
  // 创建一个弹窗实例
  var MainInstance = Object.assign({}, Main)

  // var successCb = options.success || function() {}

  MainInstance.components = {
    templateModal: options.template
  }
  MainInstance.methods.removeModal = function(instance) {
    document.body.style.overflow = 'initial'
    modalStack.pop()
    // console.log(modalStack)

    // 新添处理有滚动条的页面弹窗
    if (modalStack.length === 0) {
      document.body.style.overflow = 'initial'
    } else {
      document.body.style.overflow = 'hidden'
    }
    instance && instance.$el && instance.$el.parentNode && instance.$el.parentNode.removeChild(instance.$el)

    // setTimeout(() => {
    // instance.$el.parentNode.removeChild(instance.$el)

    //   // document.body.style.position = 'initial'
    //   // document.scrollingElement.scrollTop = scrollTop
    // }, 0)
  }
  MainInstance.methods.successCb = function(data) {
    // successCb(data)
    if (typeof options.success === 'function') {
      options.success(data)
    }
  }
  MainInstance.methods.closeCb = function(data) {
    if (typeof options.close === 'function') {
      options.close(data)
    }
  }
  var ModalConstructor = Vue.extend({ ...MainInstance, store })
  var instance = new ModalConstructor().$mount()
  instance.$props.top = options.top
  instance.$props.width = options.width
  instance.$props.params = options.params
  instance.$props.showClose = options.showClose !== undefined ? options.showClose : true
  instance.$props.closeOnClickModal = options.closeOnClickModal !== undefined ? options.closeOnClickModal : false

  modalStack.push(instance)
  // console.log(modalStack)
  document.body.appendChild(instance.$el)

  Vue.nextTick(() => {
    // instance.propsParams = options.params || {}
    instance.title = options.title
    // 让背板不滚动
    document.body.style.overflow = 'hidden'
    // scrollTop = document.scrollingElement.scrollTop
    // document.body.style.top = -scrollTop + 'px'
    // document.body.style.width = '100vw'
    // document.body.style.position = 'fixed'
  })

  return instance
}

export default HModal
